class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

public class getKthFromEnd {
    public ListNode _getKthFromEnd(ListNode head, int k) {
        if (head == null || k <= 0) {
            return null;
        }
        int count = 0;
        ListNode cur = head;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        if (k > count) {
            return null;
        }
        int c = count - k;
        ListNode kth = head;
        while (c > 0) {
            kth = kth.next;
            c--;
        }
        return kth;
    }
}
